package mulMan.gui.view;

import java.awt.event.ActionListener;
import java.awt.event.MouseListener;
import java.util.Observable;
import java.util.Observer;
import java.util.Set;

import javax.swing.JMenuItem;
import javax.swing.JPanel;
import javax.swing.JPopupMenu;
import javax.swing.JScrollPane;
import javax.swing.JTable;
import javax.swing.ListSelectionModel;

import mulMan.domain.AudioFile;
import mulMan.domain.ListOfAudioFiles;

public class AudioFilesView extends JPanel implements Observer{

	private static final long serialVersionUID = 9219019438747502674L;
	
	private Set<AudioFile> audioFiles;
	private JTable tableOfAudioFiles;
	private JPopupMenu popupMenu;
	private JMenuItem menuItemDelete;

	public JTable getTableOfAudioFiles() {
		return tableOfAudioFiles;
	}
	public void setTableOfAudioFiles(JTable tableOfAudioFiles) {
		this.tableOfAudioFiles = tableOfAudioFiles;
	}
	public JPopupMenu getPopupMenu() {
		return popupMenu;
	}
	public void setPopupMenu(JPopupMenu popupMenu) {
		this.popupMenu = popupMenu;
	}
	
	
	public AudioFilesView(Set<AudioFile> audioFiles) {
		this.audioFiles = audioFiles;

		((ListOfAudioFiles)audioFiles).addObserver(this);
		for (AudioFile iterator : audioFiles) {
			iterator.addObserver(this);
		}
		
		initView();
	}

	private void initView() {

	    this.setLayout(null);
	    this.setSize(400, 300);
	    
	    setTable();
	    setPopup();
	}
	
	private void setPopup() {
		menuItemDelete = new JMenuItem("Remove Audio File");
		popupMenu = new JPopupMenu();
		popupMenu.add(menuItemDelete);
	}
	private void setTable() {
		AudioFileTableModel audioFileTableModel = new AudioFileTableModel(audioFiles);

		tableOfAudioFiles = new JTable();
		tableOfAudioFiles.setModel(audioFileTableModel);
		tableOfAudioFiles.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
		
		JScrollPane listScroller = new JScrollPane(tableOfAudioFiles);
		listScroller.setSize(410, 340);
	    this.add(listScroller);
	}

	public void update(Observable o, Object arg) {
		resetList();
	}
	
	public void resetList() {
		
		for (AudioFile iterator : audioFiles) {
			iterator.addObserver(this);
		}
		
		tableOfAudioFiles.setModel(new AudioFileTableModel(audioFiles));
	}
	
	

	public void addTableAudioFilesListener(MouseListener tafl) {
		tableOfAudioFiles.addMouseListener(tafl);
    }
	
	public void addDeleteAudioFileListener(ActionListener dafl) {
		menuItemDelete.addActionListener(dafl);
    }
}
